package org.example.boot.usercenter.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.example.boot.usercenter.common.BaseResponse;
import org.example.boot.usercenter.common.ErrorCode;
import org.example.boot.usercenter.common.ResultUtils;
import org.example.boot.usercenter.exception.BusinessException;
import org.example.boot.usercenter.model.entity.User;
import org.example.boot.usercenter.model.request.UserLoginRequest;

import org.example.boot.usercenter.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @InterfaceName: UserController
 * @Description: 微信用户的管理接口
 * @Author: YourName
 * @Date: 2025/2/23
 */
@RequestMapping("/user")
@RestController
@Api(tags = "用户管理模块")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "登录功能接口")
    public BaseResponse<String> userLogin(@RequestBody UserLoginRequest userLoginRequest) {
        //校验请求的参数是否正确
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "没有接收到任何的参数");
        }
        //获取code
        String code = userLoginRequest.getCode();
        //校验code是否正确
        if (StringUtils.isBlank(code)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //调用 service 层的方法获取openid 和 session_key 生成token
        String Result = userService.userLoginGetCode2Session(code);
        return ResultUtils.success(Result);
    }

    @GetMapping("/current")
    @ApiOperation(value = "用户信息获取功能")
    public BaseResponse<User> getCurrent(HttpServletRequest request) {
        // 获取登录状态码
        String loginState = userService.getLoginState(request);
        User result = userService.getUserInformation(loginState);
        if (result == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(result);
    }

    @PostMapping("/update")
    @ApiOperation(value = "用户信息修改功能")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest request){
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String loginState = userService.getLoginState(request);
        int result = userService.updateUser(user,loginState);
        return ResultUtils.success(result);
    }
}
